<template>
  <div ref="playerHome" id="playerHome">
    <div ref="playerBody" class="playerBody">
      <div class="songInfo flex">
        <img @click="goBack"
             style="width: 40px;
            position: absolute;
            left: 30px;
            top: 12px"
             :src="backSrc" alt="">
        <p style="font-size: 22px;font-weight: 600">{{ songInfo.name }} </p>
        <p style="margin-top: 0px;font-size: 18px">{{ singerName }}</p>
        <img @click="goBack"
             style="width: 50px;border-radius: 50%;
            position: absolute;
            right: 30px;
            top: 12px"
             :src="user.photo" alt="">
      </div>
      <div class="modelHome" v-show="isAllSongLrc">
        <div class="img_block">
          <img style="width: 100%;height: 100%" :src="songInfo.photo" alt="">
        </div>
        <div class="songLrc">
          <div class="lrc" ref="lrc">
            <p class="lrcP"
               :class="{'active':currentTime>allKeys[index]&&currentTime<allKeys[index+1]}"
               v-for="(item,key,index) of lrcData" :key="index">
              <span>{{ item }}{{ scrollLrc(index) }}</span>
            </p>
          </div>
        </div>
      </div>
      <div class="modelLrc" v-show="!isAllSongLrc">
        <div class="allSongLrc">
          <div class="allLrc" ref="allLrc">
            <p class="allLrcP"
               :class="{'active':currentTime>allKeys[index]&&currentTime<allKeys[index+1]}"
               v-for="(item,key,index) of lrcData" :key="index">
              <span>{{ item }}{{ allScrollLrc(index) }}</span>
            </p>
          </div>
        </div>
      </div>
    </div>
    <!--   播放器控件     -->
    <div class="commonControls" v-show="isAllSongLrc">
      <!--  收藏/左滑   -->
      <div class="collectSongList">
        <img v-show="isCollect"
             @click="collectAdd"
             style="width: 30px;"
             :src="collectSrc" alt="">
        <img v-show="!isCollect"
             @click="collectDelete"
             style="width: 30px;"
             :src="collectConfirmSrc" alt="">
      </div>
      <!--   隐藏的自带音频播放器     -->
      <div class="audio flex">
        <audio ref="player"
               :src="songInfo.url"
               autoplay
               controls></audio>
      </div>
      <!--    进度条      -->
      <div style="display: flex;">
        <span style="font-size: 16px;position: absolute;left: 5%;top: -10%">
          {{currentTime>60?secondToTimeStr(currentTime):'0:'+secondToTimeStr(currentTime)}}
        </span>
        <van-progress
            style="width: 70%;
            position: absolute;left: 15%"
            :percentage="percentageTime||0"
            pivot-color="#7232dd"
            color="linear-gradient(to right, #be99ff, #7232dd)"
        />
        <span style="font-size: 16px;position: absolute;right: 5%;top: -10%">{{
            secondToTimeStr(duration)
          }}</span>
      </div>
      <!--    指令控制      -->
      <div class="sonCommonControls">
        <!--    循环播放        -->
        <div class="isLoop">
          <img @click="removeLoop "
               v-show="isLoopShow"
               style="width: 35px"
               :src="loopSrc"
               alt="">
          <img @click="addLoop"
               v-show="!isLoopShow"
               style="width: 35px"
               :src="orderSrc" alt="">
        </div>
        <!--    上一曲        -->
        <div class="nextSong">
          <img @click="nextOrPrevious('previous')"
               v-show="isAllSongLrc"
               style="width: 35px;"
               :src="previousSrc" alt="">
        </div>
        <!--      暂停        -->
        <div class="pause">
          <img @click="playPause"
               v-show="isPause"
               style="width: 60px;"
               :src="start" alt="">
          <img @click="playPause"
               v-show="!isPause"
               style="width: 60px;"
               :src="pause" alt="">
        </div>
        <!--    下一曲        -->
        <div class="nextSong">
          <img @click="nextOrPrevious('next')"
               v-show="isAllSongLrc"
               style="width: 35px;"
               :src="nextSrc" alt="">
        </div>
        <!--    歌曲列表        -->
        <img @click="isShowSongList=true"
             v-show="isAllSongLrc"
             style="width: 35px;"
             :src="songList" alt="">
      </div>
    </div>
    <!--  下页  -->
    <div class="toAllLrc">
      <img @click="changeToAllSongLrc"
           v-show="isAllSongLrc" class="move" :src="toAllSongLrc" alt="">
      <img @click="changeToAllSongHome"
           v-show="!isAllSongLrc" class="move" :src="toSongHome" alt="">
    </div>
    <!-- 歌曲列表   -->
    <div class="songList" ref="songList">
      <SongList
          :singerId="singerId"
          :activeSongId="activeSongId"
          :singerName="singerName"
          :is-show-song-list="isShowSongList"
      ></SongList>
    </div>
  </div>
</template>

<script>
import request from "../../../utils/request";
import SongList from './SongList'

export default {
  name: "PlayerHome",
  components: {
    SongList
  },
  props: {},
  data() {
    return {
      songId: Number(localStorage.getItem('currentSongId'))||24,
      songInfo: [],
      lrcData: [],
      singerId: 1,
      activeSongId: 1,
      singerName: '',
      collectSrc: require('../../../assets/collect.png'),
      collectConfirmSrc: require('../../../assets/collectConfirm.png'),
      songList: require('../../../assets/songList.png'),
      toAllSongLrc: require('../../../assets/toAllSongLrc.png'),
      toSongHome: require('../../../assets/toSongHome.png'),
      start: require('../../../assets/start.png'),
      pause: require('../../../assets/pause.png'),
      backSrc: require('../../../assets/back.png'),
      loopSrc: require('../../../assets/loop.png'),
      orderSrc: require('../../../assets/order.png'),
      previousSrc: require('../../../assets/previous.png'),
      nextSrc: require('../../../assets/next.png'),
      allKeys: [],
      currentTime: '',
      percentageTime: 1,
      duration: '',
      isAllSongLrc: true,
      isPause: false,
      collectIds: [],
      isCollect: false,
      user: JSON.parse(localStorage.getItem('user')),
      isLoopShow: false,
      isShowSongList: false
    }
  },
  methods: {
    //-1:localSongId
    localSongId(songId){
      if(songId){
        this.songId=songId
      }else {
        if(localStorage.getItem('currentSongId')){
          this.songId=Number(localStorage.getItem('currentSongId'))
        }else {
          this.songId=24
        }
      }
    },
    //0.查看是否收藏
    isCollectShow() {
      const {userId} = this.user
      request.request({
        method: "get",
        url: '/api/user/getUser',
        params: {
          userId: userId
        }
      }).then(res => {
        if (res.data.code == "200") {
          var newCollect = JSON.parse(res.data.data.collect)
          this.collectIds = newCollect
          if (this.collectIds.length > 0) {
            this.collectIds.map(item => {
              if (item == this.songId) {
                this.isCollect = false
              } else {
                this.isCollect = true
              }
            })
          } else {
            this.isCollect = false
          }
        }
      })
    },
    //1.加载歌曲数据，及歌手信息
    loadDataSource(songId) {
      request.request({
        method: "get",
        url: '/api/song/getSong',
        params: {
          songId: songId
        }
      }).then(res => {
        if (res.data.code == "200") {
          this.songInfo = res.data.data;
          this.singerName = res.data.data.singer.name
          this.singerId = res.data.data.singer.singerId
          this.filterLrc(this.songInfo)
          this.addEventHandle()
        }
      })
    },
    //2.过滤歌词
    filterLrc(values) {
      if (!values) return
      var lrc = {}
      var reg = /\[\d*:\d*(\.|:)\d*]/g
      var lyrics = values.lyric.split('\n')
      for (var i = 0; i < lyrics.length; i++) {
        var timeRegArr = lyrics[i].match(reg)
        if (!timeRegArr) continue
        //获取时间
        var t = timeRegArr[0]
        var min = parseInt(t.match(/\[\d*/i).toString().slice(1))
        var sec = parseInt(t.match(/\:\d*/i).toString().slice(1))
        var time = min * 60 + sec;
        //获取歌词
        var content = lyrics[i].replace(timeRegArr, '')
        //将对应时间作为歌词对象的key{0:'作词:李荣浩'}
        lrc[time] = content
      }
      this.lrcData = lrc
      this.allKeys=[]
      this.getAllKeys(lrc)
    },
    //3.获取所有的key
    getAllKeys(lrcData) {
      for (let key in lrcData) {
        this.allKeys.push(key)
      }
    },
    // 4. 获取音乐播放时间：
    // 4.1. 总时间
    addEventHandle() {
      this.$refs.player.addEventListener('timeupdate', (e) => {
        this.currentTime = this.$refs.player.currentTime
        this.duration = this.$refs.player.duration
      })
      //播放结束 判断loop  然后在下一首
      this.$refs.player.addEventListener('ended', () => {
        if (this.$refs.player.loop) return
        this.songId++
      })
    },
    removeEvent() {
      this.$refs.player.removeEventListener('timeupdate', this.currentTime);
      this.$refs.player.removeEventListener('timeupdate', this.duration)
    },
    // 4.2. 歌词滚动
    scrollLrc(index) {
      if (this.currentTime && (this.currentTime > this.allKeys[index] && this.currentTime < this.allKeys[index + 1])) {
        if (index < 2) {
          this.$refs.lrc.style.top = 0 + "px"
        } else {
          this.$refs.lrc.style.top = -(30 * (index - 2)) + 'px'
        }
      }
    },
    // 4.3. 音乐正在播放的时间
    allScrollLrc(index) {
      if (this.currentTime && (this.currentTime > this.allKeys[index] && this.currentTime < this.allKeys[index + 1])) {
        if (index < 9) {
          this.$refs.allLrc.style.top = 0 + 'px'
        } else {
          this.$refs.allLrc.style.top = -(30 * (index - 9)) + 'px'
        }
      }
    },
    // 5.1歌词页面
    changeToAllSongLrc() {
      this.isAllSongLrc = false
    },
    // 5.2歌曲页面
    changeToAllSongHome() {
      this.isAllSongLrc = true
    },
    // 6.暂停/播放
    playPause() {
      if (this.$refs.player.paused) {
        this.$refs.player.play()
        this.isPause = false
      } else {
        this.$refs.player.pause()
        this.isPause = true
      }
    },
    // 7.收藏歌曲
    collectAdd() {
      this.isCollect = false
      this.collectIds.push(this.songId)
    },
    // 8. 取消收藏
    collectDelete() {
      this.isCollect = true
      this.collectIds.map((item, index) => {
        if (item == this.songId) {
          this.collectIds.splice(index, 1)
        }
      })
    },
    // 9.返回
    goBack() {
      this.$router.push('/square')
      this.$bus.$emit('showNav', true)
    },
    //10.单曲循环
    addLoop() {
      this.isLoopShow = true
      this.$refs.player.setAttribute('loop', 'true')

    },
    //11.取消单曲循环
    removeLoop() {
      this.isLoopShow = false
      this.$refs.player.removeAttribute('loop')
    },
    // 12.上,下首
    nextOrPrevious(value) {
      if (value == 'next') {
        //清空上次时间,不然进度条不走
        this.currentTime=''
        // ***  先播放才能获取 当前时间,总时间  addEventHandle()
        this.songId++
        this.$nextTick(()=>{
          this.$refs.player.play();
          this.isPause=false
          this.addEventHandle();
          this.isCollectShow()
        })
      } else {
        if (this.songId > 0) {
          this.currentTime=''
          // ***  先播放才能获取 当前时间,总时间  addEventHandle()
          this.songId--;
          this.$nextTick(()=>{
            this.$refs.player.play();
            this.isPause=false
            this.addEventHandle();
            this.isCollectShow()
          })
        } else {
          console.log('到顶了');
        }
      }
    },
    // 13. 时间格式转化
    secondToTimeStr(value) {
      var theTime = parseInt(value)// 秒
      var middle = 0// 分
      var hour = 0// 小时
      if (theTime > 60) {
        middle = parseInt(theTime / 60)
        theTime = parseInt(theTime % 60)
        if (middle > 60) {
          hour = parseInt(middle / 60)
          middle = parseInt(middle % 60)
        }
      }
      var result = '' + parseInt(theTime)
      if (middle > 0) {
        result = '' + parseInt(middle) + ':' + result
      }
      if (hour > 0) {
        result = '' + parseInt(hour) + ':' + result
      }
      return result
    }
  },
  watch: {
    //监视收藏
    collectIds: {
      deep: true,
      handler(value) {
        const {userId} = this.user
        this.user.collect = JSON.stringify(value)
        request.request({
          method: "post",
          url: '/api/user/register_edit',
          params: {
            userId: userId
          },
          data: this.user
        }).then(res => {
          if (res.data.code == "200") {
          } else {
            new Error(res.data.data.msg)
          }
        })
      }
    },
    //歌曲Id
    songId: {
      immediate: true,
      deep: true,
      handler(value) {
        this.loadDataSource(value)
        this.activeSongId = value
        localStorage.setItem('currentSongId',value)
      }
    },
    //当前播放时间
    currentTime:{
      immediate: true,
      deep: true,
      handler(value) {
        let intCurrentTime=parseInt(value)
        let intDuration=parseInt(this.duration)
        if(intCurrentTime&&intDuration){
          var processTime =parseInt(intCurrentTime / intDuration * 100)
          this.percentageTime = processTime
        }
      }
    }
  },
  mounted() {
    this.$bus.$emit('showNav',false)
    this.localSongId()
    this.loadDataSource(this.songId)
    this.isCollectShow()
    this.$bus.$emit('isShow_nav', false)
    this.addEventHandle()
    //歌曲列表开关
    this.$bus.$on('closeSongList', (value) => {
      this.isShowSongList = value
    });
    //歌曲列表传过来的songId
    this.$bus.$on('setPlayerSongId', (value) => {
      this.currentTime=''
      // *** 先播放才能获取 当前时间,总时间  addEventHandle()
      this.songId = value
      this.$nextTick(() => {
        this.$refs.player.play()
        this.isPause=false
        this.addEventHandle()
        this.isCollectShow()
      })
    })
    //点击除了歌曲触发的事件
    this.$refs.playerBody.addEventListener('click', () => {
      this.isShowSongList = false
    })
  },
  beforeDestroy(){
    this.$bus.$emit('showNav',true)
  },
}
</script>

<style scoped>
#playerHome {
  width: 100%;
  height: 844px;
  position: relative;
  overflow: hidden;
  background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#ffffff), to(#eefaee)); /*背景颜色*/
}

.playerBody {
  width: 100%;
  margin-top: 15px;
}

.modelHome, .modelLrc {
  width: 100%;
}

.songInfo {
  width: 100%;
  height: 100px;
}

.commonControls {
  position: absolute;
  width: 100%;
  bottom: 70px;
}

.sonCommonControls {
  width: 100%;
  display: flex;
  margin-top: 20px;
  justify-content: space-around;
  align-items: center;
}

.img_block {
  width: 300px;
  height: 300px;
  margin-left: 45px;
  overflow: hidden;
  border-radius: 15%;
  background-color: antiquewhite;
  box-shadow: 0px 0px 10px #e2e2e2;
}

.songLrc {
  width: 100%;
  height: 150px;
  margin-top: 30px;
  overflow: scroll;
  text-align: center;
  position: relative;
}

.lrc {
  width: 100%;
  position: absolute;
  top: 0;
}

.lrcP {
  margin: 0px;
  padding: 0px;
  font-size: 20px;
  height: 30px;
  line-height: 30px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
}

.allSongLrc {
  width: 100%;
  height: 660px;
  overflow: scroll;
  text-align: center;
  position: relative;
}

.allLrc {
  width: 100%;
  position: absolute;
  top: 0;
}

.allLrcP {
  margin: 0px;
  padding: 0px;
  font-size: 20px;
  height: 30px;
  line-height: 30px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
}

.audio {
  width: 100%;
  height: 100px;
  position: absolute;
  z-index: -999;
}

.collectSongList {
  width: 100%;
  position: absolute;
  left: 45%;
  bottom: 100px;
}

.flex {
  display: flex;
  flex-direction: column;
  align-items: center;
  line-height: 16px;
}

.active {
  color: red;
  font-weight: 600;
  font-size: 22px;
}

.move {
  position: absolute;
  bottom: 20px;
  width: 120px;
  left: 36%;
  height: 35px;
  animation: clipMe 4s linear infinite;
}

@keyframes clipMe {
  0%, 100% {
    clip: rect(0px, 0px, 100px, 0px);
  }
  25% {
    clip: rect(0px, 75px, 100px, 0px);
  }
  50% {
    clip: rect(0px, 150px, 100px, 0px);
  }
  75% {
    clip: rect(0px, 300px, 100px, 0px);
  }
}
</style>